package com.bozhong.robot.bar.barcounter.utils.network;

import android.content.Context;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bozhong.robot.bar.barcounter.common.Constants;
import com.bozhong.robot.bar.barcounter.model.HttpResultVO;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Set;


/**
 * Created by Administrator on 2017/12/21.
 */

public class HttpUtil {

    private static final String TAG = HttpUtil.class.getSimpleName();
    private static final String HTTP_START = "http";
    private static HttpUtil mHttpUtil;
    private Gson mGson;
    // 连接超时时间
    private static final  int REQUEST_TIMEOUT_TIME = 60 * 1000;
    //请求队列
    private static RequestQueue mRequestQueue;
    private static String token;
    private static final String KEY_TOKEN = "Token";


    private HttpUtil(Context context){
        mGson = new Gson();
        mRequestQueue = Volley.newRequestQueue(context);
    }

    public static HttpUtil getInstance(Context context) {
        if (mHttpUtil == null) {
            synchronized (HttpUtil.class) {
                if (mHttpUtil == null) {
                    mHttpUtil = new HttpUtil(context);
                }
            }
        }

        return mHttpUtil;
    }

    public void sendPostRequest(String url, JSONObject param, HttpCallBack<HttpResultVO> httpCallBack, int requestCode) {
        if (url != null && url.indexOf(HTTP_START) == -1) {
            url = Constants.BASE_URL + url;
        }
        request(Request.Method.POST, url, param, httpCallBack, requestCode);
    }

    public void sendGetRequest(String url, JSONObject param, HttpCallBack<HttpResultVO> httpCallBack, int requestCode) {
        if (url != null && url.indexOf(HTTP_START) == -1) {
            url = Constants.BASE_URL + url;
        }
        request(Request.Method.GET, url, param, httpCallBack, requestCode);
    }

    /**
     *
     * @param method 请求方式
     * @param url 请求地址
     * @param param 请求参数
     * @param httpCallBack 回调
     * @param <T>
     */
    private void request(int method, String url, final JSONObject param, final HttpCallBack<HttpResultVO> httpCallBack, final int requestCode) {

        MyJsonRequest jsonObjectRequest = new MyJsonRequest(method, url, param,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        if (httpCallBack == null) {
                            return;
                        }

                        HttpResultVO httpResult = mGson.fromJson(response.toString(), HttpResultVO.class);
                        if (httpResult != null) {
                            httpCallBack.onSuccess(httpResult, requestCode);

                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (httpCallBack == null) {
                    return;
                }
                String msg = "";
                if (error != null && error.networkResponse != null && error.networkResponse.data != null) {
                    msg = new String(error.networkResponse.data);
                }
                httpCallBack.onFail(msg, requestCode);
            }
        });
        // jsonObjectRequest.addHeader(KEY_TOKEN, getToken());
        jsonObjectRequest.addHeader("Content-Type","application/json");
        //设置请求超时和重试
        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(REQUEST_TIMEOUT_TIME, 1, 1.0f));
        //加入到请求队列
        if (mRequestQueue != null) {
            mRequestQueue.add(jsonObjectRequest);
        }
    }

    /**
     * ParameterizedType 就是形如“ 类型<> ”的类型，如HttpCallBack<T>、List<T>、
     * Map<String,User>。比如Map<String,User>，
     * 我们通过getActualTypeArguments()方法可以获得Type[]，
     * 里面的内容是[String.class,User.class]，数组的长度由< >中的个数决定
     * @param clazz
     * @return
     */
    private Type getType(Class<?> clazz) {
        Type supClassType = clazz.getGenericSuperclass();
        Type[] types = ((ParameterizedType)supClassType).getActualTypeArguments();
        if (null != types && types.length > 0) {
            return types[0];
        }

        return null;
    }

    public static String getToken() {
        return token;
    }

    public static void setToken(String token) {
        HttpUtil.token = token;
    }
}
